package com.dems.dao.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Objects;

@Configuration
@MapperScan(basePackages = ClDataBaseConfig.PACKAGE, sqlSessionFactoryRef = "clSqlSessionFactory", sqlSessionTemplateRef = "clSqlSessionTemplate")
public class ClDataBaseConfig {

    private DataSource clDataSource;
    static final String PACKAGE = "com.dems.dao.mapper.caoliao";
    //没用到mapper的xml所以可以不用配置
    static final String LOCATION = "classpath*:mapper/caoliao/*xml";

    public ClDataBaseConfig(@Qualifier("clDataSource") DataSource clDataSource){
        this.clDataSource=clDataSource;
    }

    @Bean
    public MybatisSqlSessionFactoryBean clSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(clDataSource);
        sessionFactoryBean.setPlugins(clMybatisPlusInterceptor());
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(ClDataBaseConfig.LOCATION));
        return sessionFactoryBean;
    }

    @Bean
    public SqlSessionTemplate clSqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(Objects.requireNonNull(clSqlSessionFactory().getObject()));
    }

    @Bean
    public MybatisPlusInterceptor clMybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
}
